import 'package:environmental_les_app/common/style/colours.dart';
import 'package:environmental_les_app/common/widgets/select_image_bottom_dialog.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'big_photo_view.dart';

class AddPictureWidget extends StatefulWidget {
  const AddPictureWidget({
    super.key,
    required this.num,
    required this.imageList,
    this.tipPadding = const EdgeInsets.only(top: 8.0, bottom: 15.0),
    this.addImageStyle = AddImageStyle.solid,
  });

  /// 可以选择的最大图片数量
  final int num;
  final List<String> imageList;
  final EdgeInsetsGeometry tipPadding; // 提示信息padding
  final AddImageStyle addImageStyle; // 添加图片控件样式

  // 图片列表
  @override
  State<AddPictureWidget> createState() => _AddPictureWidgetState();
}

class _AddPictureWidgetState extends State<AddPictureWidget> {
  final String defaultImgFlag = "default";

  List<String> images = [];

  @override
  void initState() {
    images.add(defaultImgFlag);
    logger.i("initState: $images");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                mainAxisSpacing: 10.0,
                crossAxisCount: 3,
                crossAxisSpacing: 8.0),
            itemCount: images.length,
            itemBuilder: (context, index) => images[index] == defaultImgFlag
                ? InkWell(onTap: () => _onAddImage(), child: _defaultImg())
                : InkWell(
                    onTap: () => _onBigImg(index, images),
                    child: Stack(
                      children: [
                        Container(
                          clipBehavior: Clip.hardEdge,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4.0),
                          ),
                          child: ImageWidget.loadNetImage(images[index],
                              width: double.infinity, height: double.infinity),
                        ),
                        Align(
                          alignment: Alignment.topRight,
                          child: InkWell(
                            onTap: () => _onDeleteImg(index),
                            child: _deleteWidget(),
                          ),
                        )
                      ],
                    )),
          ),
          Padding(
            padding: widget.tipPadding,
            child: Text(
              "最多可上传${widget.num}张照片，支持jpg/jpeg/png格式",
              style: const TextStyle(fontSize: 12.0, color: Colours.text09C),
            ),
          ),
        ],
      ),
    );
  }

  /// 删除控件
  _deleteWidget() {
    return Container(
      width: 18.0,
      height: 18.0,
      decoration: const BoxDecoration(
        color: Colours.appMain,
        borderRadius: BorderRadius.only(
          topRight: Radius.circular(4.0),
          bottomLeft: Radius.circular(10.0),
        ),
      ),
      child: const Icon(Icons.close, color: Colors.white, size: 12.0),
    );
  }

  /// 默认图片
  _defaultImg() {
    return GFBorder(
      padding: EdgeInsets.zero,
      dashedLine: const [3, 3.8],
      color: widget.addImageStyle == AddImageStyle.dash
          ? Colours.text09C
          : Colors.transparent,
      type: GFBorderType.rRect,
      radius: const Radius.circular(4.0),
      child: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          color: widget.addImageStyle == AddImageStyle.dash
              ? Colors.transparent
              : Colours.bgColor,
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: const Icon(Icons.add, color: Colours.text09C, size: 30.0),
      ),
    );
  }

  /// 查看大图
  /// [index] 当前点击的图片索引
  /// [list] 图片列表
  _onBigImg(int index, List<String> list) {
    List<String> tList = [];
    tList.addAll(list.where((element) => element != defaultImgFlag));
    Get.to(BigPhotoView(
      imageList: tList,
      selectIndex: index,
    ));
  }

  /// 添加图片
  _onAddImage() {
    Get.bottomSheet(SelectImageBottomDialog(onCallback: (url) {
      if (url.isEmpty) return;
      images.insert(images.length - 1, url);
      _setDefaultImg();
      setState(() {});
    }));
  }

  /// 删除图片
  /// [index] 当前点击的图片索引
  _onDeleteImg(int index) {
    images.removeAt(index);
    _setDefaultImg();
    setState(() {});
  }

  /// 添加、删除默认图片
  /// [num] 可以选择的最大图片数量
  /// [images] 图片列表
  /// [defaultImgFlag] 默认图片标识
  /// 添加、删除默认图片 ，最后返回图片列表，不包含默认图片标识,最多一张时删除后添加默认图片标识
  _setDefaultImg() {
    // 获取操作list
    var list = images;

    logger.i("images:_setDefaultImg $images");

    if (list.isEmpty) {
      list.add(defaultImgFlag);
    }

    if (list.length > widget.num && list.last == defaultImgFlag) {
      // 移除最后一个图片图标
      list.remove(defaultImgFlag);
    } else if (list.length <= widget.num && list.last != defaultImgFlag) {
      // 添加最后一个添加图片图标
      list.add(defaultImgFlag);
    }
    // 重新设置list

    // 移除默认图片标识
    widget.imageList.clear();
    widget.imageList.addAll(list.where((element) => element != defaultImgFlag));
    logger.i("widget.imageList: ${widget.imageList}");
  }
}

enum AddImageStyle {
  solid, // 填充颜色
  dash, // 虚线
}
